<template>
	<el-form label-suffix="：" :model="formData" label-width="auto" style="max-width: 600px">
		<el-form-item :label="item.label" v-for="(item,index) in formOption" :key="item.key || index">
			<component 
        :is="item.componentsName" 
        v-model="formData[item.key]" 
        v-bind="item.props" 
        :placeholder="item.placeholder || getPlaceholder(item)"
        clearable
      >
        <!-- 特殊处理 el-select 的 options -->
        <template v-if="item.componentsName === 'el-select' && item.options">
          <el-option
            v-for="option in item.options"
            :key="option.value"
            :label="option.label"
            :value="option.value">
          </el-option>
        </template>
        <!-- 特殊处理 el-radio-group 的 options -->
        <template v-if="item.componentsName === 'el-radio-group' && item.options">
          <el-radio
            v-for="option in item.options"
            :key="option.value"
            :label="option.value" 
            >{{ option.label }}</el-radio
          >
        </template>
      </component>
		</el-form-item>
	</el-form>
</template>

<script>
	export default {
		name: 'formBuild',
		props: {
			formOption: {
				type: Array,
				default: () => []
			}
		},
		data() {
			return {
				formData: {}
			}
		},
		created() {
			this.init()
		},
		
		methods: {
			init() {
				this.formData = {}
				this.formOption.forEach((item) => {
					// 确保 key 存在，否则 vue 会有警告
					if (item.key) {
						this.formData[item.key] = item.value !== undefined ? item.value : '';
					}
				})
			},
			formDataChange(newVal) {
				this.$emit('formDataChange', newVal)
			},
			getPlaceholder(item) {
				if (item.componentsName && item.componentsName.includes('select')) {
					return `请选择${item.label}`;
				}
				if (item.componentsName && item.componentsName.includes('date')) {
					return `请选择日期`;
				}
				return `请输入${item.label}`;
			},
			resetFormFields() {
				this.init();
			}
		},
		mounted() {
			this.$watch('formData', (newData) => {
				this.formDataChange(newData)
			}, { deep: true, immediate: false })
		}
	}
</script>

<style>
</style>